﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ELab.Message
{
    public class CommandMessage : ICommandMessage
    {
        public CommandMessage()
        {
        }

        public CommandMessage(byte[] data)
        {
            if (data == null || data.Length < 6 || data[0] != (byte)MessageType.Command)
                throw new Exception("Invalidate data bytes of Command message");

            byte[] lengBytes = new byte[] { data[2], data[3], data[4], data[5] };
            int length = BitConverter.ToInt32(lengBytes, 0);
            if (length != data.Length)
                throw new Exception("Invalidate data bytes of Command message");

            var commandType = data[1];
            if (!Enum.IsDefined(typeof(CommandType), commandType))
                throw new Exception("Invalidate data bytes of Command message");

            this.CommandType = (CommandType)commandType;

            var body = data.Skip(6).Take(length - 1).ToArray();
            this.Body = body;
        }

        public MessageType MessageType
        {
            get { return MessageType.Command; }
        }

        public CommandType CommandType { get; set; }

        public byte[] Body { get; set; }

        public byte[] Data
        {
            get
            {
                var data = new byte[] { (byte)this.MessageType, (byte)this.CommandType, 0, 0, 0, 0 };

                if (this.Body != null && this.Body.Length > 0)
                    data = data.Append<byte>(this.Body);

                //Update length of message
                var bytesLength = BitConverter.GetBytes(data.Length);
                bytesLength.CopyTo(data, 2);

                return data;
            }
        }
    }
}
